<template>
  <div>
    <a-input v-model:value="kw" placeholder="请输入" w-200px></a-input>

    <div flex justify-between items-center mt-4>
      <div pl-4 text-xl font-bold>对齐类目</div>
      <a-button @click="handleAdd">新建对齐类目</a-button>
    </div>

    <vue-draggable
      v-model="startData.mapping_categories"
      :animation="150"
      flex
      flex-wrap
      gap-4
      min-h-200px
      py-30px
    >
      <a-card
        :body-style="{ padding: '0 20px 0 20px', cursor: 'move!important' }"
        v-for="item in list"
        :key="item.category_code + item.website_code"
        w-250px
      >
        <div h-128px flex-center>
          <img :src="item.website_img_url" class="w-full max-h-128px" alt="" />
        </div>
        <div mt-50px>{{ item.category_name }}</div>
        <div mb-20px>{{ item.category_code }}</div>
        <template #actions>
          <a-tooltip color="#108ee9" title="查看源网站">
            <a-button
              type="link"
              @click="goSource(item)"
              :icon="h(EyeOutlined)"
            ></a-button>
          </a-tooltip>
          <a-tooltip color="#108ee9" title="类目拆分">
            <a-button
              type="link"
              :icon="h(SplitCellsOutlined)"
              @click="goSplit(item)"
            ></a-button>
          </a-tooltip>
          <a-tooltip color="#108ee9" title="删除">
            <a-button
              type="link"
              :icon="h(DeleteOutlined)"
              danger
              @click="remove(item)"
            ></a-button>
          </a-tooltip>
        </template>
      </a-card>
    </vue-draggable>

    <div text-center>
      <a-space>
        <a-button
          type="primary"
          @click="next"
          :disabled="!startData.mapping_categories.length"
        >
          下一步
        </a-button>
        <a-button
          type="primary"
          :disabled="!startData.mapping_categories.length"
          @click="save"
        >
          保存
        </a-button>
        <a-button @click="reset">重置</a-button>
      </a-space>
    </div>

    <Add ref="addRef" :webs="startData.mapping_categories" />
  </div>
</template>

<script lang="ts" setup>
import type { WebSiteWithCategory } from '@/types/website';
import {
  DeleteOutlined,
  ExclamationCircleOutlined,
  SplitCellsOutlined,
  EyeOutlined,
} from '@ant-design/icons-vue';
import { JobStep } from '../Step';
import type { FetchProcess, JumpType, StartData, UpdateProcess } from '../type';
import { Modal } from 'ant-design-vue';
import { createVNode } from 'vue';
import { useRemove } from '../useRemove';
import router from '@/router';
import { VueDraggable } from 'vue-draggable-plus';
import Add from './add.vue';

const props = defineProps<{
  stepData: JobStep;
  fetchProcess: FetchProcess;
  updateProcess: UpdateProcess;
}>();

const kw = ref('');

const { stepData, fetchProcess, updateProcess } = toRefs(props);
const { removeWebSite } = useRemove(stepData);

const emits = defineEmits<{
  jump: [params: JumpType];
}>();

const startData = ref<StartData>(cloneDeep(props.stepData.data as StartData));
if (!startData.value.mapping_categories) {
  startData.value.mapping_categories = [];
}

const list = computed(() => {
  if (!kw.value) return startData.value.mapping_categories;
  return startData.value.mapping_categories.filter(item => {
    return item.category_name.toLowerCase().includes(kw.value.toLowerCase());
  });
});

const addRef = ref<InstanceType<typeof Add>>();
const handleAdd = async () => {
  addRef.value?.add((website, categories) => {
    const list = categories.map(category => {
      return {
        website_code: website.websiteCode,
        website_img_url: website.websiteImgUrl,
        website_name: website.websiteName,
        website_url: website.websiteUrl,
        category_code: category.categoryCode,
        category_href: category.categoryHref,
        category_img_url: category.categoryImgUrl,
        category_name: category.categoryName,
        id: category.id,
        nav_breadcrumb: '',
      };
    });
    startData.value.mapping_categories.push(...list);
  });
};

const remove = (category: WebSiteWithCategory) => {
  const idx = startData.value.mapping_categories.findIndex(item =>
    compare(item, category, ['category_code', 'website_code']),
  );
  const find = startData.value.mapping_categories[idx];
  startData.value.mapping_categories.splice(idx, 1);
  stepData.value.isEdit = true;
  // effect of remove website
  removeWebSite(find);
};

const next = async () => {
  emits('jump', {
    process_name: 'CONDITION_RELATION',
    callback: save,
    isNext: true,
  });
};

const save = show => {
  stepData.value.updateStep('START', startData.value);
  return new Promise((resolve, _reject) => {
    updateProcess.value().then(res => {
      if (res.code == 'ok') {
        show && message.success('保存成功');
        stepData.value.isEdit = false;
        resolve('ok');
      } else {
        Modal.confirm({
          title: '提示',
          width: '700px',
          closable: true,
          footer: null,
          content: res.message.split(/\s/).map((item, idx) => {
            return createVNode(
              'div',
              idx == 0 ? { style: 'font-size: 16px;font-weight: bold' } : {},
              item,
            );
          }),
        });
      }
    });
  });
};

const reset = () => {
  Modal.confirm({
    title: '提示',
    okType: 'danger',
    icon: createVNode(ExclamationCircleOutlined),
    okText: '是',
    cancelText: '否',
    content: '未保存的操作将会丢失，是否继续？',
    onOk: async () => {
      await fetchProcess.value('START');
      startData.value = cloneDeep(props.stepData.data as StartData);
    },
  });
};

const goSource = item => {
  if (item.category_href) {
    window.open(item.category_href);
  }
};

const goSplit = (item: WebSiteWithCategory) => {
  router.push({
    path: '/split',
    query: {
      websiteCode: item.website_code,
      categoryId: item.id,
    },
  });
};

defineExpose({
  change: process_name => {
    emits('jump', {
      process_name,
      callback: save,
    });
  },
});
</script>
